package lg.minecraft.plugin.library.common;

import lg.minecraft.plugin.library.LGLibrary;
import lg.minecraft.plugin.library.config.LGBaseConfig;
import lg.minecraft.plugin.library.task.BaseTask;
import org.bukkit.plugin.Plugin;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * @author langle__
 * @version 1.0
 */
public class ObserverThread extends BaseTask {

    public static final ObserverThread INSTANCE = new ObserverThread();

    private final Map<Plugin, Set<FileListener>> PLUGIN_FILE_LISTENERS = new HashMap<>();

    private final LGLibrary plugin;

    public ObserverThread() {
        this.plugin = LGLibrary.getInstance();
    }

    @Override
    public void run() {
        PLUGIN_FILE_LISTENERS.values().forEach(fileListeners -> fileListeners.forEach(FileListener::canLoadConfig));
    }

    public void start() {
        this.runTaskTimerAsynchronously(plugin, 20, 20);
    }

    public void addFileListener(FileListener listener) {
        Plugin plugin = listener.getPlugin();
        Set<FileListener> fileListeners = PLUGIN_FILE_LISTENERS.computeIfAbsent(plugin, k -> new HashSet<>());
        fileListeners.add(listener);
    }

    public void addFileListener(LGBaseConfig config) {
        this.addFileListener(new FileListener(config));
    }

    public void removeFileListener(FileListener listener) {
        Plugin plugin = listener.getPlugin();
        Set<FileListener> fileListeners = PLUGIN_FILE_LISTENERS.get(plugin);
        if (fileListeners != null) {
            fileListeners.remove(listener);
        }
    }

    public void removeFileListener(Plugin plugin) {
        PLUGIN_FILE_LISTENERS.remove(plugin);
    }

    public void clearListeners() {
        PLUGIN_FILE_LISTENERS.clear();
    }

}
